import Taro from '@tarojs/taro'

/**
 * 登录函数
 * @param {boolean} refresh 是否强制刷新
 * @returns {Promise<{openId: string, success: boolean, message: string}>} 登录结果
 */
export async function loginFun(refresh = false) {
  try {
    // 如果不强制刷新，先检查缓存
    if (!refresh) {
      const openId = Taro.getStorageSync('openId')
      const expireTime = Taro.getStorageSync('loginExpireTime')
      const now = Date.now()

      // 如果缓存有效，直接返回
      if (openId && expireTime && now < expireTime) {
        console.log('使用缓存的登录信息，openId:', openId)
        return {
          success: true,
          openId,
          message: '使用缓存的登录信息'
        }
      }
    }

    // 需要重新登录
    console.log('登录过期或未登录，重新获取openId')

    // 调用微信登录获取code
    const loginRes = await Taro.login()
    if (!loginRes || !loginRes.code) {
      console.error('获取微信登录code失败')
      return {
        success: false,
        message: '获取微信登录凭证失败'
      }
    }

    console.log('获取到登录code:', loginRes.code)

    // 调用云函数获取openId
    try {
      const result = await Taro.cloud.callFunction({
        name: 'login'
      })

      if (result && result.result && result.result?.userInfo?.openId) {
        const openId = result.result.userInfo.openId
        console.log('登录成功，openId:', openId)

        // 将openId存储到本地缓存
        Taro.setStorageSync('openId', openId)

        // 设置过期时间，7天后过期
        const newExpireTime = Date.now() + 7 * 24 * 60 * 60 * 1000
        Taro.setStorageSync('loginExpireTime', newExpireTime)

        return {
          success: true,
          openId,
          message: '登录成功'
        }
      } else {
        console.error('登录接口返回数据异常:', result)
        return {
          success: false,
          message: '登录接口返回数据异常'
        }
      }
    } catch (error) {
      console.error('调用云函数登录失败:', error)
      return {
        success: false,
        message: '调用云函数登录失败',
        error
      }
    }
  } catch (error) {
    console.error('登录过程发生错误:', error)
    return {
      success: false,
      message: '登录过程发生错误',
      error
    }
  }
}

/**
 * 获取当前登录用户的openId
 * @returns {string|null} 当前登录用户的openId，如果未登录则返回null
 */
export function getCurrentOpenId() {
  return Taro.getStorageSync('openId') || null
}

/**
 * 检查用户是否已登录
 * @returns {boolean} 是否已登录
 */
export function isLoggedIn() {
  const openId = Taro.getStorageSync('openId')
  const expireTime = Taro.getStorageSync('loginExpireTime')
  const now = Date.now()

  return !!(openId && expireTime && now < expireTime)
}

/**
 * 退出登录
 */
export function logout() {
  Taro.removeStorageSync('openId')
  Taro.removeStorageSync('loginExpireTime')
}
